class PictureController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions  only accept POST requests
    def allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        if(!params.max) params.max = 10
        [ pictureList: Picture.list( params ) ]
    }

    def show = {
        def picture = Picture.get( params.id )

        if(!picture) {
            flash.message = "Picture not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ picture : picture ] }
    }

    def delete = {
        def picture = Picture.get( params.id )
        if(picture) {
            picture.delete()
            flash.message = "Picture ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = "Picture not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def picture = Picture.get( params.id )

        if(!picture) {
            flash.message = "Picture not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ picture : picture ]
        }
    }

    def update = {
        def picture = Picture.get( params.id )
        if(picture) {
            picture.properties = params
            if(!picture.hasErrors() && picture.save()) {
                flash.message = "Picture ${params.id} updated"
                redirect(action:show,id:picture.id)
            }
            else {
                render(view:'edit',model:[picture:picture])
            }
        }
        else {
            flash.message = "Picture not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def picture = new Picture()
        picture.properties = params
        return ['picture':picture]
    }

    def save = { // TODO Modify save method to create all images
        
        def picture = new Picture(params)
        def listing=picture.listing
        def multiPartFile = request.getFile('file')
        def imaging = new Imaging()
        def images = null
        if (multiPartFile && !multiPartFile.isEmpty()) {
            if (multiPartFile.getSize() > Image.MAX_SIZE) {
                picture.errors.rejectValue('file','picture.maxSize.exceeded',
                ['file','Picture', Image.MAX_SIZE] as Object[],
                'property [{0}] of class[{1}] image file is too big (maximum [{2}] bytes')
            }
            else {
                try {
                    images = imaging.createAll(listing, picture, multiPartFile.inputStream)
                }
                catch(Exception ex) {
                    log.error("picture save",ex)
                    picture.errors.rejectValue('file','picture.file.unrecognized',
                    ['file','Picture',multiPartFile.originalFilename] as Object[],
                    'property [{0}] of class[{1}] image [{2}]: type not recognized')
                }
            }
        }
        else {
            picture.errors.rejectValue('file','picture.file.missing',
            ['file','Picture',''] as Object[],
            'property [{0}] of class[{1}] no file specified')
        }
        if (images && !picture.hasErrors()) {
                boolean result = false
                Picture.withTransaction { status ->
                    images.each { image ->
                        picture.addToImages(image)
                    }
                    result = picture.save()
                    listing.addToPictures(picture)
                    listing.picturesCount++
                    listing.save()
                }
                if (result) {
                    flash.message = "Picture ${picture.id} creted"
                    redirect(action: show, id: picture.id)
                }
                else {
                    render(view: 'create', model: [picture: picture])
                }
            
        }
        else {
            render (view: 'create', model: [picture: picture])
        }
    }

    def view = {
     def picture = Picture.get(params.id)
     def size = params.size ? Integer.parseInt(params.size) : Image.Small
     def image = picture ? Image.findByPictureAndSize(picture, size) : null
     if (picture && image) {
         response.setContentType(image.contentType)
         response.setContentLength(image.data.size())
         response.setHeader('filename', image.filename())
         OutputStream out = response.outputStream
         out.write(image.data)
         out.close()
     }
     else {
         response.sendError(404)
     }
   }

}